package Test.PracticeCAS;

import java.util.concurrent.CountDownLatch;

/**
 * 模拟CAS执行原理
 */
public class demo03 {
    volatile static int count = 0;

    public static void request() throws InterruptedException {

        Thread.sleep(5);
//        count++;
        int expectCount;
        while (!compareAndSwap(expectCount = getCount(), expectCount + 1)) ;

    }

    /**
     * @param expectCount 老值，或者也叫原来获取到的count值
     * @param newCount    新值，也就是需要赋值回去的值
     * @return
     */
    public static synchronized boolean compareAndSwap(int expectCount, int newCount) {
        if (getCount() == expectCount) {
            count = newCount;
            return true;
        } else {
            return false;
        }
    }

    public static int getCount() {
        return count;
    }

    public static void main(String[] args) throws InterruptedException {

        long startTime = System.currentTimeMillis();
        int size = 1000;
        CountDownLatch countDownLatch = new CountDownLatch(size);

        for (int i = 0; i < size; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        for (int j = 0; j < 10; j++) {
                            request();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        countDownLatch.countDown();
                    }

                }
            }).start();
        }

        countDownLatch.await();
        long endTime = System.currentTimeMillis();

        System.out.println(endTime - startTime);
        System.out.println(count);
    }

}